package org.adit.spring.hibernate.parser;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Scanner;

import org.adit.spring.hibernate.parser.entity.FleetEngineInput;
import org.adit.spring.hibernate.parser.entity.Result;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class SPPoster {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {

			Scanner scanner = new Scanner(new FileInputStream("c:/PA_MAO_INTEC.CSV"));
			int jobCounter = 1;
			while (scanner.hasNextLine()) {

				scanner.useDelimiter(",");
				String os = scanner.next();
				String end = scanner.next();
				String num = scanner.next();
				String cidade = scanner.next();

				// Send data
				URL url = new URL("http://184.73.171.214:12001/");
				URLConnection conn = url.openConnection();
				conn.setDoOutput(true);
				OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
				String xmlIn = "<?xml version=\"1.0\"?><KRETTAXML>	<REQUEST>		<ACAO>Geocode</ACAO>		" + "<CIDADE>"+cidade+"</CIDADE>		" + "<ESTADO>am</ESTADO>		" + "<LOGRADOURO>" + end.replace(".", "") + "</LOGRADOURO>		"
						+ "<NUMERO>" + num + "</NUMERO>		" + "<SISTEMCOORD>WGS84</SISTEMCOORD>	</REQUEST></KRETTAXML>";
				wr.write(xmlIn);
				wr.flush();

				// Get the response
				BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

				String line;

				XStream xstream = new XStream(new DomDriver());
				xstream.alias("krettaxml", KrettaXml.class);
				xstream.alias("response", Response.class);
				xstream.alias("geocode", Geocode.class);
				xstream.alias("ponto", Ponto.class);
				xstream.alias("cidade", Cidade.class);

				while ((line = rd.readLine()) != null) {
					///System.out.println(line);
					KrettaXml fleetEngineInput = (KrettaXml) xstream.fromXML(line.toLowerCase().toString());
					//System.out.println(end);
					//System.out.println(num);
					int count = 0;
					if (fleetEngineInput.getResponse().getGeocode().getListapontos() != null) {

						for (Ponto ponto : fleetEngineInput.getResponse().getGeocode().getListapontos()) {
							if (count == 0) {
								
							    String xxx = "<Job Id=\"J_"+os.trim()+">     <Demands>    <Demand Ind=\"1\">1</Demand>   </Demands>     <Pickup>   <X>"+ponto.getX()+"</X>    <Y>"+ponto.getY()+"</Y>     </Pickup>   </Job>";
								
								System.out.println(xxx);
							        
							    jobCounter++;
							}
							count++;
						}
					} else {
						System.out.println(0 + "," + 0);

					}
				}
				wr.close();
				rd.close();
			}
		} catch (Exception e) {
		}

	}
}
